<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan
 *
 */

class DecisionsController extends AppController {

    /**
     * Define $name
     *
     */
    var $name = 'Decisions';
    /**
     * Define $helpers
     *
     */
    var $helpers = array('Html', 'Form', 'DatePicker','Comment','Text','Javascript','MultiFile','Ajax','Numbering');
    /**
     * Define $components
     *
     */
    var $components = array('MultiFile','RequestHandler','Auth');
    /**
     * Define $uses
     *
     */
    var $uses = array ('Notification','User','Comment','Template','Attachment','Decision','Item');

    /**
     * Describe view
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function view($committee,$id = null) {
        $this->User->unbindmodel(array('hasMany'=>array('Announcement','Meetingtodo','Groupstatus','Userstatus')),false);
        $this->Decision->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        
        if (!$id) {
            $this->Session->setFlash(__('Invalid Decision.', true));
            $this->redirect(array('action'=>'index'));
        }
        $decisions=$this->Decision->getCurrentStatus($id);
        $decisions=$this->Decision->unset_nonImpstatus($decisions,null);
        
        // get files and comments for each status
        foreach($decisions['Userstatus'] as $sid=>$status){
            $attach=$this->Attachment->find('all',array('conditions'=>array('model'=>'Userstatus','foreign_key'=>$status['id'])));
            $comment=$this->Comment->find('all',array('conditions'=>array('model'=>'Userstatus','foreign_key'=>$status['id']),'order'=>'updated desc'));
            if(count($attach)){
                $decisions['Userstatus'][$sid]['MultiFile']['additionalfiles']=$attach;
            }
            if(count($comment)){
                foreach($comment as $cid=>$curcomment){
                    $users=$this->User->find('first',array('fields'=>array('name','job_title'),'conditions'=>array('User.id'=>$curcomment['Comment']['user_id'])));
                    $comment[$cid]['Comment']['user_name']=$users['User']['name'];
                    $comment[$cid]['Comment']['job_title']=$users['User']['job_title'];
                }
                $decisions['Userstatus'][$sid]['UserstatusComment']=$comment;
            }
        }
        foreach($decisions['Groupstatus'] as $sid=>$status){
            $attach=$this->Attachment->find('all',array('conditions'=>array('model'=>'Groupstatus','foreign_key'=>$status['id'])));
            $comment=$this->Comment->find('all',array('conditions'=>array('model'=>'Groupstatus','foreign_key'=>$status['id']),'order'=>'updated desc'));
            if(count($attach)){
                $decisions['Groupstatus'][$sid]['MultiFile']['additionalfiles']=$attach;
            }
            if(count($comment)){
                foreach($comment as $cid=>$curcomment){
                    $users=$this->User->find('first',array('fields'=>array('name','job_title'),'conditions'=>array('User.id'=>$curcomment['Comment']['user_id'])));
                    $comment[$cid]['Comment']['user_name']=$users['User']['name'];
                    $comment[$cid]['Comment']['job_title']=$users['User']['job_title'];
                }
                $decisions['Groupstatus'][$sid]['GroupstatusComment']=$comment;
            }
        }
        $this->data=$decisions;
        
        //check permission
        $secretariat=$this->Decision->Meeting->Attendance->isSecretariat($decisions['Decision']['meeting_id'],$this->Auth->user('id'));
        $this->set('secretariat',$secretariat);
        if($secretariat==0){
            $permission=$this->permission;
            $allow=0;
            foreach($decisions['User'] as $user){
                
                if(!empty($permission['Userstatus']['Create'])){
                    $allow++;
                    $this->set('allow_add_user_status_'.$user['id'],true);
                }elseif(($this->Auth->user('id')==$user['id']) && $permission['Userstatus -Own']['Create'] ==1){
                    $allow++;
                    $this->set('allow_add_user_status_'.$user['id'],true);
                }
            }
            foreach($decisions['Group'] as $group){
                if($permission['Groupstatus']['Create']==1){
                    $allow++;
                    $this->set('allow_add_group_status_'.$group['id'],true);
                }else{
                    $userlist=$this->Decision->Group->userList($group['id']);
                    if((in_array($this->Auth->user('id'),$userlist)) && $permission['Groupstatus -Own']['Create'] ==1){
                        $allow++;
                        $this->set('allow_add_group_status_'.$group['id'],true);
                    }
                }
            }
        }
            
        $chairperson =$this->Decision->Meeting->Attendance->getChairperson($decisions['Meeting']['id']);
        $this->set(compact('chairperson'));
        //all decision data
        $this->set('decision1',$decisions);
        
        $this->Decision->Userstatus->Behaviors->detach('MultiFile');
        $this->Decision->Userstatus->Behaviors->detach('Comment');
        $this->Decision->Groupstatus->Behaviors->detach('MultiFile');
        $this->Decision->Groupstatus->Behaviors->detach('Comment');
        // get history of status
        $users = Set::extract('/User/id',$decisions);
        $groups = Set::extract('/Group/id',$decisions);
        $this->set('user_history_status',$this->Decision->Userstatus->getHistory($users,$decisions['Decision']['id']));
        $this->set('group_history_status',$this->Decision->Groupstatus->getHistory($groups,$decisions['Decision']['id']));
   
        //decision data with distinct user and group
        $decisions=$this->Decision->needupdating($decisions,1);
        $this->set('decision',$decisions);
        
        //$allStatus --> check whether all the status are approve or not?
        $allStatus =1;
        if(isset($decisions['Group'][0])||isset($decisions['User'][0])){
            $allStatus = 0;
        }else{
            $userstatus_approve=set::extract($decisions,'Userstatus.{n}.approved');
            $groupstatus_approve=set::extract($decisions,'Groupstatus.{n}.approved');
            if(!empty($userstatus_approve)){
                $allStatus=array_product($userstatus_approve);
            }
            if(!empty($groupstatus_approve)){
                $allStatus*=array_product($groupstatus_approve);
            }
        }
        $this->set('allStatus',$allStatus);
        if($this->Auth->user('superuser')==0){
            if($secretariat==0 && $this->Auth->user('id')!=$chairperson['User']['id']){
                if($decisions['Decision']['approved']==1){
                    if(empty($permission['Decision -Accepted']['View'])){
                        $this->notpermit();
                    }
                }elseif(!empty($allow)){
                    if(empty($permission['Decision -Assigned']['View'])){
                        $this->notpermit();
                    }
                }elseif(empty($permission['Decision']['View'])){
                    $this->notpermit();
                }
            }
        }
        $key=null;
        if(in_array($this->Session->read('history'),array('getmultidata','committees/find'))){
            $key=$this->Session->read('key');
        }
        $this->set('key',$key);
        $this->set('minuteapproval',$this->Decision->Meeting->Notification->checksent($decisions['Decision']['meeting_id'],'minutes approved'));
    }

    /**
     * Describe doaddmany
     *
     * @param $committee
     * @return null
     */
    function doaddmany($committee){
        $this->dcommittee=$this->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$this->dcommittee);
        if(!empty($this->data)){
            $meeting_id=$this->data['Decision']['meeting_id'];
            $meeting=$this->Decision->Meeting->read(null,$meeting_id);
            $minutes=$meeting['Meeting']['minutes_raw'];
            $order=0;
            foreach($this->data['Decision'] as $dname=>$ddat){
                if($dname!='meeting_id'){
                    if(isset($decision)) unset($decision);
                    $decision['Decision']['meeting_id']=$meeting_id;
                    if(isset($ddat['Item'])){
                        $decision['Decision']['item_id']=$ddat['Item'];
                    }
                    elseif(isset($ddat['ItemName'])){
                        $itemdata['name']=$ddat['ItemName'];
                        $itemdata['short_name']=$ddat['ItemShortName'];
                        $itemdata['committee_id']=$this->dcommittee['Committee']['id'];
                        $this->Item->create();
                        $this->Item->save($itemdata);
                        $decision['Decision']['item_id']=$this->Item->getLastInsertID();
                    }
                    if(isset($ddat['Deadline'])) $decision['Decision']['deadline']=$ddat['Deadline'];
                    $decision['Decision']['description']=$ddat['Decision'];
                    $decision['Decision']['committee_id']=$this->dcommittee['Committee']['id'];
                    if(!$decision['Decision']['item_id']){
                        $decision['Decision']['item_id']=0;
                    }
                    $decision['Decision']['ordering']=$order++;
                    $this->Decision->create();
                    $this->Decision->save($decision);
                    $stripd=preg_replace('|^<p>(.*)</p>$|','\1',$ddat['Decision']);
                    $minutes=str_replace($ddat['OriDecision'],'<a name=\''.$this->Decision->getLastInsertID().'\'></a>'.$stripd,$minutes);
                    $decision_id=$this->Decision->getLastInsertID();
                    if(isset($ddat['User'])){
                        foreach($ddat['User'] as $user_id){
                            if($user_id){
                                $user['DecisionsUser']['decision_id']=$decision_id;
                                $user['DecisionsUser']['user_id']=$user_id;
                                $this->Decision->DecisionsUser->save($user);
                                unset($this->Decision->DecisionsUser->id);
                            }
                        }
                    }
                    if(isset($ddat['Group'])){
                        foreach($ddat['Group'] as $group_id){
                            if($group_id){
                                $group['DecisionsGroup']['decision_id']=$decision_id;
                                $group['DecisionsGroup']['group_id']=$group_id;
                                $this->Decision->DecisionsGroup->save($group);
                                unset($this->Decision->DecisionsGroup->id);
                            }
                        }
                    }
                    unset($this->Decision->id);
                }
            }
            $minutes=str_replace(array('{{','}}','((','))','[[',']]','###'),'',$minutes);
            $meeting['Meeting']['minutes']=$minutes;
            $this->Decision->Meeting->save($meeting);
            $this->redirect(array('committee'=>$committee,'controller'=>'decisions','action'=>'minutes','id'=>$meeting_id));
        }
    }

    /**
     * Describe verifyminutes
     *
     * @param $committee
     * @return null
     */
    function verifyminutes($committee) {
        $this->dcommittee=$this->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$this->dcommittee);
        if(isset($this->params['meetingid'])){  //meetingid is provided so please load the meeting data
            $meeting=$this->Decision->Meeting->read(null,$this->params['meetingid']);
            $this->set('meeting',$meeting);
            $meeting['Meeting']['id']=$meeting['Meeting']['id'];
            $meeting['Meeting']['minutes']=$meeting['Meeting']['minutes'];
        }
        if(!empty($this->data) && isset($this->data['Decision']['meeting_id'])){  //if it actually came from a form which added a new meeting, save the data (minutes_raw) first
            $meeting['Meeting']['id']=$this->data['Decision']['meeting_id'];
            $meeting['Meeting']['minutes_raw']=$this->data['Decision']['data'];
            $this->Decision->Meeting->save($meeting);
        }
        $comid=$this->Decision->Meeting->getCommitteeId($meeting['Meeting']['id']);
        $items=$this->Decision->Item->find('all',array('fields'=>array('id','short_name','name'),'conditions'=>array('committee_id'=>$comid)));
        $this->set('items',$items);
        $this->set('users',$this->Decision->User->getUsersPerCommitteeList($comid));
        $ddat=$this->Decision->extractMinutes($meeting['Meeting']['minutes_raw']);
        $tdat=null;
        if($ddat && is_array($ddat)){
            $tdat=$this->Decision->filterData($ddat,$meeting['Meeting']['id']);
        }
        if(!is_array($tdat)){  //didn't find anything spectacular (ie: no decision). Save the minutes and get out of here
            $minutes=str_replace(array('{{','}}','((','))','[[',']]','###'),'',$this->data['Decision']['data']);
            $meeting['Meeting']['minutes']=$minutes;
            $this->Decision->Meeting->save($meeting);
            $this->redirect(array('controller'=>'decisions','action'=>'minutes','id'=>$meeting['Meeting']['id'],'committee'=>$this->dcommittee['Committee']['short_name']));
        }
        $tdat=$this->Decision->itemList($tdat,$this->dcommittee['Committee']['id']);
        $tdat=$this->Decision->userList($tdat,$this->dcommittee['Committee']['id']);
        $tdat=$this->Decision->groupList($tdat,$this->dcommittee['Committee']['id']);
        $this->set('decisions',$tdat);
        $this->set('meeting_id',$meeting['Meeting']['id']);
    }

    /**
     * Describe addminutes
     *
     * @param $committee
     * @return null
     */
    function addminutes($committee) {
        $this->Decision->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Meeting->Behaviors->detach('MultiFile');
        $this->Decision->Meeting->Behaviors->detach('Comment');
        
        if(!empty($this->data) && isset($this->data['Decision']['meeting_id'])){
        }
        if(isset($this->params['meetingid'])){
            $meeting=$this->Decision->Meeting->read(null,$this->params['meetingid']);
            if($this->dcommittee['Committee']['id']!=$meeting['Meeting']['committee_id']){
                $this->notpermit();
            }
            $sec=$this->Decision->Meeting->Attendance->isSecretariat($meeting['Meeting']['id'],$this->Auth->user('id'));
            if(empty($sec)){
                if(empty($this->permission['Decision']['Create'])){
                    $this->notpermit();
                }
            }
            
/*
            if($this->Session->check('minute_data')){
                $meeting['Meeting']['minutes_raw']=$this->Session->read('minute_data');
            }
            elseif(strlen($meeting['Meeting']['minutes_raw'])==0){
                $meeting['Meeting']['minutes_raw']=$this->dcommittee['Committee']['minute_template'];
            }
*/          $meeting['Meeting']['minutes_raw']=null;
            $this->set('meeting',$meeting);
        }
    }

    /**
     * Add decisions in minutes layout
     *
     * @param $committee
     * @return null
     */
    function minutes($committee) {
        $this->Committee->recursive=-1;
        $this->Decision->Behaviors->detach('MultiFile');
        $this->Decision->Behaviors->detach('Comment');
        $this->Decision->Meeting->Behaviors->detach('MultiFile');
        $this->Decision->Meeting->Behaviors->detach('Comment');
        if (!empty($this->data)) {
            $this->Decision->create();
            $this->data['Decision']['committee_id']=$this->dcommittee['Committee']['id'];
            $lastnumber=$this->Decision->find('first',array(
                'conditions'=>array(
                    'Decision.meeting_id'=>$this->data['Decision']['meeting_id'],
                ),
                'order'=>array(
                    'Decision.ordering desc'
                ),
                'contain'=>false,
                'fields'=>array(
                    'ordering',
                ),
            ));
            $this->data['Decision']['ordering']=$lastnumber['Decision']['ordering']+1;
            $this->Decision->save($this->data);

            if(isset($this->data['Decision']['id'])){
                $this->Decision=ClassRegistry::init('Decision','model');
                $this->senddecision($this->data['Decision']['id'],$this->Decision->getLastInsertID());     
            }
        }
        $this->__minuteContent();
        
        //check permission
        $sec=$this->Decision->Meeting->Attendance->isSecretariat($this->meetingid,$this->Auth->user('id'));
        if(empty($sec)){
            if(empty($this->permission['Decision']['Create'])){
                $this->notpermit();
            }
        }
        $this->set('items',$this->Decision->Item->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']),'order'=>'Item.name ASC')));
        $this->set('groups',$this->Decision->Meeting->User->Group->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
        $this->set('users', $this->Decision->Meeting->User->getUsersPerCommitteeList($this->dcommittee['Committee']['id'], $this->meetingid));
        if($this->Session->check('decision_id')){
            $mdecision=$this->Session->read('decision_id');
            if($mdecision['meeting_id']==$this->params['id']){
                $this->set('paste',1);
            }
        }
    }


    function __minuteContent(){
        $this->Decision->unbindModel(array('hasAndBelongsToMany'=>array('User','Group'),'hasMany'=>array('Userstatus','Groupstatus'),'belongsTo'=>array('Item','Meeting','Committee')),false);
        if(isset($this->params['id'])){ // coming from the url
            $this->meetingid = $this->params['id'];
        } else { // coming from after submitting form
            $this->meetingid = $this->data['Decision']['meeting_id'];
        }
        $this->Decision->Meeting->unbindModel(array('hasMany'=>array('Decision','Notification','Todo','Committee')),false);
        $this->meetingList = $this->Decision->Meeting->read(null,$this->meetingid);
        $this->set('meeting',$this->meetingList);
        if($this->dcommittee['Committee']['id']!=$this->meetingList['Meeting']['committee_id']){
            $this->notpermit();
        }
        
        $decisions = $this->Decision->find('all',array('conditions'=>array('meeting_id'=>$this->meetingid),'order'=>'Decision.lft asc'));
        $new_decision = array();
        foreach ( $decisions as $decision) {
            //unset($decision['MultiFile']);
            $sql = "SELECT id, file, filename, private FROM attachments WHERE model='Decision' AND foreign_key =".$decision['Decision']['id'];
            $result = mysql_query($sql);
            $rows = mysql_num_rows($result);
            $attachment_list = array();
            if ( $rows > 0 ) {
                for ( $i = 0; $i<$rows; $i++) {
                    $attachment_result = mysql_fetch_array($result);
                    array_push($attachment_list,$attachment_result );
                }
                array_push($decision, $attachment_list);
            }
            array_push($new_decision, $decision);
        }

        $decisions = $new_decision;
        $this->new_decision = $this->Decision->userdecisionlist($decisions);
        $levels = $this->Decision->getLevels($this->meetingid);
        $arrows = $this->Decision->getArrows($levels, $this->meetingid);
        $this->set('decisions',$this->new_decision);
        $this->set('levels',$levels);
        $this->set('meetingid',$this->meetingid);
        $this->set('arrows', $arrows);
        if ($this->RequestHandler->isAjax()) {  
            $this->viewPath = 'elements'.DS.'minutes';
            $this->render('displayminutes');
        }
    }
    
    function printminutes($committee,$id){
        $this->Decision->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Workflow','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Behaviors->detach('Comment');
        $this->Decision->Behaviors->detach('MultiFile');
        $this->Decision->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Meeting->Behaviors->detach('MultiFile');
        $this->Decision->Meeting->Behaviors->detach('Comment');

        $MeetingId = $this->params['id'];
        $CommitteeId = $this->Decision->CommitteeToId($committee);
        
        // get all invitees - present n absent
        $this->loadModel('Attendance');
        $invitees = $this->Attendance->getAttendees($CommitteeId,$MeetingId);
        $didntcome = $this->Attendance->getAttendees($CommitteeId,$MeetingId,0);
        $this->set('invitees', $invitees);
        $this->set('didntcome', $didntcome);
   
        //get secretariat
        $secretariat=array();
        $assign_as=set::extract($invitees,'{n}.Attendance.attend_as');
        
        if(!empty($assign_as)){
            foreach($assign_as as $a=>$aa){
                if($aa==1){
                    $secretariat[]=$invitees[$a];
                }
            }
        }
        $assign_as=set::extract($didntcome,'{n}.Attendance.attend_as');
        if(!empty($assign_as)){
            foreach($assign_as as $a=>$aa){
                if($aa==1){
                    $secretariat[]=$didntcome[$a];
                }
            }
        }
        $this->set('secretariat',$secretariat[0]);
        $secretariat_id=set::extract($secretariat,'{n}.User.id');
        $issecretariat=in_array($this->Auth->user('id'),$secretariat_id)?1:0;
        $this->set('isSec',$issecretariat);
        //check approved
        $minute_approved=$this->Notification->checkSent($id,'minutes approved');
        $this->set('minutes_approved',$minute_approved);
        
        // get chairperson
        $chairperson_detail =$this->Decision->Meeting->Attendance->getChairperson($MeetingId);
        $this->set('chairperson_detail',$chairperson_detail);
        if($chairperson_detail['User']['id']==$this->Auth->user('id')){
            $chairperson=1;
            $this->set('chairperson',1);
            $meeting=$this->Decision->Meeting->find('first',array('conditions'=>array('Meeting.id'=>$MeetingId)));
            $prev=$this->Decision->Meeting->find('first',array(
                'conditions'=>array(
                    'Meeting.committee_id'=>$this->dcommittee['Committee']['id'],
                    'Meeting.deleted=0',
                    'or'=>array(
                        'Meeting.meeting_date<\''.$meeting['Meeting']['meeting_date'].'\'',
                        'and'=>array(
                            'Meeting.meeting_date=\''.$meeting['Meeting']['meeting_date'].'\'',
                            'Meeting.id<'.$MeetingId,
                        )
                    )
                ),
                'order'=>'Meeting.meeting_date DESC'
            ));
            $this->set('prev',$prev);
        }
        $permission=$this->Session->read('permission');
        $this->set('permission',$permission);
        //check permission on this page
        if(empty($chairperson) && empty($issecretariat) && empty($permission['Minute approval']['Create'])){
            $permit=$this->minutePermission($minute_approved);
            if(empty($permit)){
                $this->notpermit();
            }
        }

        if (isset($this->params['pass']['2'])) $this->Session->setFlash($this->params['pass']['2']);        
        
        $this->set('report', 1);
        $this->set('minuteType', $this->Decision->checkMinuteType($committee));
        
        $this->__minuteContent();
        $this->loadModel('Comment');
        foreach($this->new_decision as $d=>$decision){
           $this->new_decision[$d]['Decision']['MinuteComment']=$this->Comment->find('all',array('conditions'=>array('Comment.model'=>'Minute','Comment.foreign_key'=>$decision['Decision']['id'])));
        }
        $this->set('decisions',$this->new_decision);
        
        $this->layout='decision';
        $this->render('printminutes');
        
    }

    /**
     * Describe addDecision
     *
     * @param $committee
     * @return null
     */
    function addDecision(){
        if (!empty($this->data)) {
            $this->Decision->create();
            $this->data['committee_id']=$this->dcommittee['Committee']['id'];
            $lastnumber=$this->Decision->find('first',array(
                'conditions'=>array(
                    'Decision.meeting_id'=>$this->data['meeting_id'],
                ),
                'order'=>array(
                    'Decision.ordering desc'
                ),
                'contain'=>false,
                'fields'=>array(
                    'ordering',
                ),
            ));
            $this->data['ordering']=$lastnumber['Decision']['ordering']+1;
            
            if ($this->Decision->save($this->data)) {

                $lastId = $this->Decision->getLastInsertID();
                $sql = "UPDATE decisions SET item_id = '".$this->data[$this->data['item_name']]."' WHERE id = ".$lastId;
                mysql_query($sql);
                $this->Attachment->query("UPDATE attachments SET field='additionalfiles' WHERE id=".$this->Attachment->getLastInsertID());
                $Users = $this->data['User']['User'];
                foreach ( $Users as $user) {
                    $sql = "INSERT INTO decisions_users ( decision_id, user_id ) VALUES ('".$lastId."', '".$user."')";
                    mysql_query($sql);
                }

                $Groups = $this->data['Group']['Group'];
                foreach ( $Groups as $group) {
                    $sql = "INSERT INTO decisions_groups ( decision_id, group_id ) VALUES ('".$lastId."', '".$group."')";
                    mysql_query($sql);
                }
            }

        }
    }

    function minuteform($committee,$meetingid,$node=null,$id=null) {
        if ($this->RequestHandler->isAjax()) {
            $this->Decision->unbindModel(array('hasMany'=>array('Userstatus','Groupstatus'),'belongsTo'=>array('Item','Meeting','Committee')),false);
            $decisions = $this->Decision->find('all',array('conditions'=>array('meeting_id'=>$this->params['meetingid']),'order'=>'Decision.lft asc'));
            if (isset($node) && !empty($node)) $this->set('node',$node);
            $this->set('items',$this->Decision->Item->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']),'order'=>'Item.name ASC')));
            $this->set('groups',$this->Decision->Meeting->User->Group->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
            $this->set('users', $this->Decision->Meeting->User->getUsersPerCommitteeList($this->dcommittee['Committee']['id'], $meetingid));
            $this->set('meeting',$this->Decision->Meeting->findById($meetingid));
            $this->set('decisions',$decisions);
            $this->set('id',$id);
            $this->set('meetingid',$meetingid);
            $this->viewPath = 'elements'.DS.'minutes';
            $this->render('minute_form');
        }
    }
    
    function actionby($committee) {

        if ($this->RequestHandler->isAjax()) {
            $this->set('groups',$this->Decision->Meeting->User->Group->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
            $this->set('users', $this->Decision->Meeting->User->getUsersPerCommitteeList($this->dcommittee['Committee']['id']));
            $this->viewPath = 'elements'.DS.'minutes';
            $this->render('action_by');
        }
    }
    
    /**
     * Describe add
     *
     * @param $committee
     * @return null
     */
    function add($committee,$meetingid=null,$itemid=null) {
        $this->Decision->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Meeting->Behaviors->detach('MultiFile');
        $this->Decision->Meeting->Behaviors->detach('Comment');
        $this->Decision->unbindModel(array('hasMany'=>array('Userstatus','Groupstatus')),false);
        
        
        if(!empty($this->params['meetingid'])){
            $meeting=$this->Decision->Meeting->findById($this->params['meetingid']);
            $this->set('meeting',$meeting);
            
            if($this->dcommittee['Committee']['id']!=$meeting['Meeting']['committee_id']){
                $this->notpermit();
            }
            $sec=$this->Decision->Meeting->Attendance->isSecretariat($meetingid,$this->Auth->user('id'));
            if(empty($sec)){
                if(empty($this->permission['Decision']['Create'])){
                    $this->notpermit();
                }
            }
        }
        if(!empty($this->params['itemid'])){
            $item=$this->Decision->Item->read(null,$this->params['itemid']);
            $this->set('item',$item);
            
            if($this->dcommittee['Committee']['id']!=$item['Item']['committee_id']){
                $this->notpermit();
            }
            if(empty($this->permission['Decision']['Create'])){
                $this->notpermit();
            }
        }
        if (!empty($this->data)) {
            $this->Decision->create();
            $this->data['Decision']['committee_id']=$this->dcommittee['Committee']['id'];
            $lastnumber=$this->Decision->find('first',array(
                'conditions'=>array(
                    'Decision.meeting_id'=>$this->data['Decision']['meeting_id'],
                ),
                'order'=>array(
                    'Decision.ordering desc'
                ),
                'contain'=>false,
                'fields'=>array(
                    'ordering',
                ),
            ));
            $this->data['Decision']['ordering']=$lastnumber['Decision']['ordering']+1;
            
            if ($this->Decision->save($this->data)) {
                $this->Session->setFlash(__('The Decision has been saved', true));
                if(isset($this->data['Decision']['returnpage'])){
                    $this->redirect($this->data['Decision']['returnpage']);
                }else{
                    $this->redirect(array('committee'=>$this->dcommittee['Committee']['id'],'action'=>'index'));
                }
            } else {
                $this->Session->setFlash(__('The Decision could not be saved. Please, try again.', true));
            }
        }
        $this->set('items',$this->Decision->Item->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']),'order'=>'Item.name Asc')));
        $this->set('meetings',$this->Decision->Meeting->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
        $this->set('groups',$this->Decision->Meeting->User->Group->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
        $this->set('users', $this->Decision->Meeting->User->getUsersPerCommitteeList($this->dcommittee['Committee']['id'], isset($this->params['meetingid'])?$this->params['meetingid']:null));
        $this->set('returnpage',$this->referer(null,true));
    }



    /**
     * Create notifications when comments are made to the decision
     *
     * @param $decision_id 
     * @param $comment_id
     * @return null
     */
    function sendcomment($decision_id,$comment_id){
        $this->Decision->Behaviors->detach('Comment');
        $decision=$this->Decision->read(null,$decision_id);
        $this->Comment->bindModel(array(
            'belongsTo'=>array(
                'User',
            )
        ),false);
        $comment=$this->Comment->read(null,$comment_id);
        //insert needed data in $decision
        $decision['Comment']['comment']=$comment['Comment']['description'];
        $decision['Comment']['user']=$comment['User']['name'];
        $decision['Link']['decision']=array('committee'=>urlencode($decision['Committee']['short_name']),'controller'=>'decisions','action'=>'view','id'=>$decision_id);
        $template=$this->Template->processTemplate('decision comment',$decision);
        if($template){
            $users=$this->Decision->decisionimplementor($decision_id);
            foreach($users as $userid){
                $user=$this->Decision->Meeting->User->find('first',array('conditions'=>array('User.id'=>$userid)));
                $this->Decision->Meeting->sendEmail($decision['Meeting'],$template,$user['User'],NULL);
            }
        }
    }


    /**
     * Describe promote
     *
     * @param $committee
     * @param $meetingid
     * @param $id
     * @return null
     */
    function promote($committee,$meetingid=null,$id = null) {
        $this->Decision->promote($id);
        $this->redirect($this->referer(null,true));
    }

    /**
     * Describe demote
     *
     * @param $committee
     * @param $meetingid
     * @param $id
     * @return null
     */
    function demote($committee,$meetingid=null,$id = null) {
        $this->Decision->demote($id);
        $this->redirect($this->referer(null,true));
    }

    /**
     * Describe notifyusers
     *
     * @param $committee
     * @param $meetingid
     * @param $id
     * @return null
     */
    function announcedecision($committee,$meetingid=null,$id = null) {
        $this->dcommittee=$this->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$this->dcommittee);
        $this->Decision->notifyuser($id);
        $this->Session->setFlash(__('Email has been sent to the implementors', true));
        $this->redirect($this->referer(null,true));
    }

    /**
     * move up
     *
     * @param $decisionid
     * @return null
     */
    function promote2() {       
        $this->Decision->DecisionMoveUp($this->params['id']);
        $this->redirect($this->referer(null,true));
    }

    /**
     * move down
     *
     * @param $decisionid
     * @return null
     */
    function demote2() {
        $this->Decision->DecisionMoveDown($this->params['id']);
        //$this->Decision->movedown($this->params['id']);
        $this->redirect($this->referer(null,true));
    }

    /**
     * Describe edit
     *
     * @param $committee
     * @param $meetingid
     * @param $id
     * @return null
     */
    function edit($committee,$meetingid=null,$id = null) {
        $this->Decision->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Meeting->Behaviors->detach('MultiFile');
        $this->Decision->Meeting->Behaviors->detach('Comment');
        $this->Decision->unbindModel(array('hasMany'=>array('Userstatus','Groupstatus')),false);
        
        $this->set('dcommittee',$this->dcommittee);
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Decision', true));
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->data)) {
            $this->Decision->curUser=$this->Auth->user('id');
            $this->data['Decision']['committee_id']=$this->dcommittee['Committee']['id'];
            if ($this->Decision->save($this->data)) {
                if(isset($this->data['Decision']['returnpage'])){
                    if(isset($this->data['DecisionComment']['Comment']) && configure::read('e_decisioncomment')==1){
                        $this->Comment=ClassRegistry::init('Comment','model');
                        $this->sendcomment($this->data['Decision']['id'],$this->Comment->getLastInsertID());
                    }
                    $this->redirect($this->data['Decision']['returnpage']);
                }
                else{
                    $this->Session->setFlash(__('The Decision has been saved', true));
                    $this->redirect(array('action'=>'index'));
                }
            } else {
                $this->Session->setFlash(__('The Decision could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Decision->read(null, $id);
            $meeting=$this->Decision->Meeting->read(null,$this->data['Decision']['meeting_id']);
            $item=$this->Decision->Item->read(null,$this->data['Decision']['item_id']);
            
            //check permission
            if($this->dcommittee['Committee']['id']!=$meeting['Meeting']['committee_id']){
                $this->notpermit();
            }
            
            if($this->Auth->user('superuser')==0){
                $sec=$this->Decision->Meeting->Attendance->isSecretariat($meeting['Meeting']['id'],$this->Auth->user('id'));
                if(empty($sec)){
                    $permiss=$this->decisionPermission($this->data);
                    if(empty($permiss['Edit'])){
                        $this->notpermit();
                    }
                }
            }
            
        }
        $this->set('returnpage',$this->referer(null,true));
        $this->set('groups',$this->Decision->Meeting->User->Group->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
        $this->set('items',$this->Decision->Item->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']),'order'=>'Item.name ASC')));
        $this->set('users', $this->Decision->Meeting->User->getUsersPerCommitteeList($this->dcommittee['Committee']['id']));
        $this->set(compact('meeting','item'));
        if ($this->RequestHandler->isAjax()) {
            $this->set('node',$this->params['node']);
            $this->set('meetingid',$this->params['meetingid']);
            $this->set('id',$this->params['id']);
            if (isset($this->data['MultiFile'])) { $this->set('attachment',$this->data['MultiFile']['additionalfiles'.$this->data['Decision']['parent_id']]); }
            $this->viewPath = 'elements'.DS.'minutes';
            $this->render('edit_minute');
        }
    }

    function decisionedit($committee,$meetingid=null,$id = null) {
        $this->dcommittee=$this->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$this->dcommittee);
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Decision', true));
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->data)) {
            $this->Decision->curUser=$this->Auth->user('id');
            $this->data['Decision']['committee_id']=$this->dcommittee['Committee']['id'];
            if ($this->Decision->save($this->data)) {
                $this->Session->setFlash(__('The Decision has been saved', true));
                if(isset($this->data['Decision']['returnpage'])){
                    if(isset($this->data['DecisionComment']['Comment'])){
                        $this->Comment=ClassRegistry::init('Comment','model');
                        $this->sendcomment($this->data['Decision']['id'],$this->Comment->getLastInsertID());
                    }
                    $this->redirect($this->data['Decision']['returnpage']);
                }
                else{
                    $this->redirect(array('action'=>'index'));
                }
            } else {
                $this->Session->setFlash(__('The Decision could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Decision->read(null, $id);
            $meeting=$this->Decision->Meeting->read(null,$this->data['Decision']['meeting_id']);
            $item=$this->Decision->Item->read(null,$this->data['Decision']['item_id']);

            $sql = "SELECT id, file, filename FROM attachments WHERE model='Decision' and foreign_key = ".$this->params['node'];
            $result = mysql_query($sql);
            
            $rows = mysql_num_rows($result);
            $attachment_list = array();
            if ( $rows > 0 ) {
                for ( $i = 0; $i<$rows; $i++) {
                    $attachment_result = mysql_fetch_array($result);
                    array_push($attachment_list,$attachment_result );
                }
            }
            $this->data['Multifile']['additionalfiles']=$attachment_list;
        }
        $this->set('returnpage',$this->referer(null,true));
        $this->set('groups',$this->Decision->Meeting->User->Group->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
        $this->set('items',$this->Decision->Item->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']),'order'=>'Item.name ASC')));
        $this->set('users', $this->Decision->Meeting->User->getUsersPerCommitteeList($this->dcommittee['Committee']['id']));
        $this->set(compact('meeting','item'));
        if ($this->RequestHandler->isAjax()) {
            $this->set('attachment', $attachment_list);
            $this->set('node',$this->params['node']);
            $this->set('meetingid',$this->params['meetingid']);
            $this->set('id',$this->params['id']);
            $this->viewPath = 'elements'.DS.'minutes';
            $this->render('edit_minute');
        }
    }

    function editDecision() {

        if ( $this->data ) {
            $lastnumber=$this->Decision->find('first',array(
                'conditions'=>array(
                    'Decision.meeting_id'=>$this->data['meeting_id'],
                ),
                'order'=>array(
                    'Decision.ordering desc'
                ),
                'contain'=>false,
                'fields'=>array(
                    'ordering',
                ),
            ));
            $this->data['ordering']=$lastnumber['Decision']['ordering']+1;
            $id = $this->data['node'];
            $this->data['Decision']['description']=$this->data['description'];
            $this->data['Decision']['id']=$id;
            $this->Decision->save($this->data);
            $sql = "UPDATE decisions SET item_id = '".$this->data[$this->data['item_name']]."' WHERE id = ".$id;
            mysql_query($sql);
            
            $sql = "DELETE FROM decisions_users WHERE decision_id =".$id;
            mysql_query($sql);
            $sql = "DELETE FROM decisions_groups WHERE decision_id =".$id;
            mysql_query($sql);
        
            $Users = $this->data['User']['User'];
            foreach ( $Users as $user) {
                $sql = "INSERT INTO decisions_users ( decision_id, user_id ) VALUES ('".$id."', '".$user."')";
                mysql_query($sql);
            }

            $Groups = $this->data['Group']['Group'];
            foreach ( $Groups as $group) {
                $sql = "INSERT INTO decisions_groups ( decision_id, group_id ) VALUES ('".$id."', '".$group."')";
                mysql_query($sql);
            }

            $this->Attachment->query("UPDATE attachments SET field='additionalfiles' WHERE id=".$this->Attachment->getLastInsertID());
            
            /*$this->Decision->save($this->data);
            $insertid = $this->Decision->getLastInsertID();
            $sql = "UPDATE decisions SET item_id = '".$this->data[$this->data['item_name']]."' WHERE id = ".$insertid;
            mysql_query($sql);

            $sql = "SELECT committee_id, ordering, parent_id, lft, rght FROM decisions WHERE id =".$id;
            $result = mysql_query($sql);
            $result_Array = mysql_fetch_array($result);

            $sql = "UPDATE decisions SET committee_id = '".$result_Array['committee_id']."', ordering='".$result_Array['ordering']."',parent_id='".$result_Array['parent_id']."', lft='".$result_Array['lft']."', rght='".$result_Array['rght']."' WHERE id =".$insertid;
            mysql_query($sql);
            
            $sql = "UPDATE decisions SET deleted = 1 WHERE id =".$id;
            mysql_query($sql);
            
            $sql = "UPDATE attachments SET foreign_key = '".$insertid."' WHERE foreign_key =".$id;
            mysql_query($sql);

            $sql = "UPDATE decisions SET parent_id = '".$insertid."' WHERE parent_id =".$id;
            mysql_query($sql);
            
            $sql = "UPDATE comments SET foreign_key = '".$insertid."' WHERE foreign_key =".$id." and model='Minute'";
            mysql_query($sql);

            $sql = "DELETE FROM decisions_users WHERE decision_id =".$id;
            mysql_query($sql);
            $sql = "DELETE FROM decisions_groups WHERE decision_id =".$id;
            mysql_query($sql);
        
            $Users = $this->data['User']['User'];
            foreach ( $Users as $user) {
                $sql = "INSERT INTO decisions_users ( decision_id, user_id ) VALUES ('".$insertid."', '".$user."')";
                mysql_query($sql);
            }

            $Groups = $this->data['Group']['Group'];
            foreach ( $Groups as $group) {
                $sql = "INSERT INTO decisions_groups ( decision_id, group_id ) VALUES ('".$insertid."', '".$group."')";
                mysql_query($sql);
            }*/

        }

    }

    /**
     * Describe delete
     *
     * @param $committee
     * @param $itemid
     * @param $id
     * @return null
     */
    function delete($committee,$itemid = null,$id = null) {
        $decision=$this->Decision->find('first',array('conditions'=>array('Decision.id'=>$id)));
        
        //check permission
        if($this->params['meetingid']){
            if($this->params['meetingid']!=$decision['Decision']['meeting_id']){
                $this->notpermit();
            }
        }
        $meeting=$this->Decision->Meeting->find('first',array('conditions'=>array('Meeting.id'=>$decision['Decision']['meeting_id'])));
        if($this->dcommittee['Committee']['id']!=$meeting['Meeting']['committee_id']){
            $this->notpermit();
        }
        if($this->Auth->user('superuser')==0){
            $sec=$this->Decision->Meeting->Attendance->isSecretariat($decision['Decision']['meeting_id'],$this->Auth->user('id'));
            if(empty($sec)){
                $permiss=$this->decisionPermission($decision);
                if(empty($permiss['Delete'])){
                    $this->notpermit();
                }
            }
        }
        
        if ($this->RequestHandler->isAjax()) {
            $this->Decision->delete($this->params['id']);
            $this->Decision->unbindModel(array('hasAndBelongsToMany'=>array('User','Group'),'hasMany'=>array('Userstatus','Groupstatus'),'belongsTo'=>array('Item','Committee')),false);
            $decisions = $this->Decision->find('all',array('conditions'=>array('meeting_id'=>$this->params['meetingid']),'order'=>'Decision.lft asc'));
            $levels = $this->Decision->getLevels($this->params['meetingid']);
            $arrows = $this->Decision->getArrows($levels, $this->params['meetingid']);
            $decisions = $this->Decision->userdecisionlist($decisions);
            $this->set('arrows',$arrows);
            $this->set('levels',$levels);
            $this->set('meetingid',$this->params['meetingid']);
            $this->set('decisions',$decisions);
            $this->set('node','1');
            $this->set('id',$id);
            
            $this->viewPath = 'elements'.DS.'minutes';
            $this->render('displayminutes');
        } else {
            if (!$id) {
                $this->Session->setFlash(__('Invalid id for Decision', true));
            }
            $this->Decision->delete($id);
            $this->Session->setFlash(__('Decision deleted', true));
            $this->redirect($this->referer(null,true));
        }
    }

    function importfile($committee){
        $this->dcommittee=$this->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$this->dcommittee);
        $this->Session->write('minute_data','hello');
        $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'controller'=>'decisions','action'=>'addminutes','meetingid'=>$this->params['meetingid']));
    }
    
    //file remove
    function deletefile($attID){
        $id = $this->params['id'];
        $delaction = $this->params['action'];
        
        if ( $delaction = "deletefile" && $id > 0 ) {
            $sql = "SELECT file FROM attachments WHERE id=".$id;
            $result = mysql_query($sql);
            $rows = mysql_num_rows($result);
            
            if ( $rows > 0 ) {
                $loc = mysql_fetch_array($result);
                $dir = getcwd();
                $new_loc = $loc['file'];
                $sql = "DELETE FROM attachments WHERE id =".$id;
                mysql_query($sql);
                $dir = $dir."/".$new_loc;
                if (file_exists($dir)) {
                    unlink($dir);
                }
                
            }
        }
    }
    
    
     /**
     * Describe add grouped status 
     *
     * @param $committee
     * @param $meetingid
     * @param $id
     * @return null
     */
    function status($committee,$meetingid=null,$id = null) {
        $this->Decision->unbindModel(array('hasMany'=>array('Userstatus','Groupstatus')),false);
        $this->Decision->Behaviors->detach('MultiFile');
        $this->Decision->Behaviors->detach('Comment');

        $this->set('dcommittee',$this->dcommittee);
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Decision', true));
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->data)) {
            if ($this->Decision->save($this->data)) {
                $this->Session->setFlash(__('The grouped status has been saved', true));
                if(isset($this->data['Decision']['returnpage'])){
                    $this->redirect($this->data['Decision']['returnpage']);
                }
            } else {
                $this->Session->setFlash(__('The grouped status could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Decision->read(null, $id);
        }
        
        //check permission
        if($this->Auth->user('superuser')==0){
            $sec=$this->Decision->Meeting->Attendance->isSecretariat($this->data['Meeting']['id'],$this->Auth->user('id'));
            if(empty($sec)){
                $this->notpermit();
            }
        }
        
        $this->set('returnpage',$this->referer(null,true));
    }
    
    /*describe approved decision
     * */
    function approvedecision($committee,$id = null,$value=1) {
        $this->data['Decision']['id'] = $id;
        $this->data['Decision']['approved'] = $value;
        if ($this->Decision->save($this->data,false)){
            $this->Session->setFlash(sprintf(__('Decision has been put into the minutes',true)));
            $this->redirect(array('committee'=>$committee,'id'=>$this->data['Decision']['id'],'action'=>'view'));          
        }
    }
    
    function approvegroupStatus($committee,$id = null) {
        $this->Decision->Groupstatus->recursive=0;
        $this->Decision->Groupstatus->unbindmodel(array('belongsTo'=>array('Committee','User','Group')));
        $groupstatus=$this->Decision->Groupstatus->findById($id);

        //check permission
        if($this->Auth->user('superuser')==0){
            $sec=$this->Decision->Meeting->Attendance->isSecretariat($groupstatus['Decision']['meeting_id'],$this->Auth->user('id'));
            if(empty($sec)){
                $this->notpermit();
            }
        }

        $this->data['Groupstatus']['id'] = $id;
        $this->data['Groupstatus']['approved'] = 1;
        
        if ($this->Decision->Groupstatus->save($this->data,false)){
            $this->Session->setFlash(sprintf(__('Status has been accepted',true)));
        }
    }
          
    function approveUserStatus($committee,$id = null) {
        $this->Decision->Userstatus->recursive=0;
        $this->Decision->Userstatus->unbindmodel(array('belongsTo'=>array('Committee','User','Updater')));
        $userstatus=$this->Decision->Userstatus->findById($id);

        //check permission
        if($this->Auth->user('superuser')==0){
            $sec=$this->Decision->Meeting->Attendance->isSecretariat($userstatus['Decision']['meeting_id'],$this->Auth->user('id'));
            if(empty($sec)){
                $this->notpermit();
            }
        }
        
        $this->data['Userstatus']['id'] = $id;
        $this->data['Userstatus']['approved'] = 1;
        
        if ($this->Decision->Userstatus->save($this->data,false)){
            $this->Session->setFlash(sprintf(__('Status has been accepted',true)));
        }
    }    
    
    //save minute comment
    function addcomment($committee){
        if(isset($this->data['Decision']['returnpage'])){
            if(isset($this->data['MinuteComment']['Comment'])){
                $this->Comment=ClassRegistry::init('Comment','model');
                $this->Comment->create();
                $this->data['MinuteComment']['Comment']['model']='Minute';
                $this->data['MinuteComment']['Comment']['foreign_key']=$this->data['Minute']['id'];
                $this->data['MinuteComment']['Comment']['user_id']=$this->Auth->user('id');
                $this->Comment->save($this->data['MinuteComment']);
                
                $this->redirect($this->data['Decision']['returnpage']);
            }
        }
    }   
    
    //send comment to secretariat
    function minutecomment($committee,$id){
        $this->Decision->Behaviors->detach('Comment');
        $this->Decision->Behaviors->detach('MultiFile');
        $this->Decision->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Decision->Meeting->Behaviors->detach('MultiFile');
        $this->Decision->Meeting->Behaviors->detach('Comment');
        $this->__minuteContent();
        
        $this->meetingList['Link']['decision']=array('committee'=>urlencode($this->dcommittee['Committee']['short_name']),'controller'=>'decisions','action'=>'printminutes','id'=>$id);
        $user=$this->Decision->User->find('first',array('conditions'=>array('User.id'=>$this->Auth->user('id'))));
        $this->meetingList['Comment']['user']=$user['Title']['short_name'].' '.$user['User']['name'];
        $template=$this->Template->processTemplate('minute comment',$this->meetingList);
        
        //process the comments
        $pos1=strpos($template['Template']['template'],'%%content to repeat');
        $pos2=strpos($template['Template']['template'],'content to repeat%%');
        $len=strlen('%%content to repeat');
        $content_repeat=substr($template['Template']['template'],$pos1+$len,$pos2-$pos1-$len);
        $content='';
        $this->loadModel('Comment');
        foreach($this->new_decision as $d=>$decision){
            $comment=$this->Comment->find('all',array('conditions'=>array('Comment.model'=>'Minute','Comment.foreign_key'=>$decision['Decision']['id'])));
            if($comment){
                foreach($comment as $ckey=>$comm){
                    $this->new_decision[$d]['Comment']['comment']=$comm['Comment']['description'];
                    $content.=$this->Decision->replacetemplate($content_repeat,$this->new_decision[$d]);
                }
            }
        }
        $template['Template']['template']=str_replace('%%content to repeat'.$content_repeat.'content to repeat%%',$content,$template['Template']['template']);
        
        $this->Decision->Meeting->Attendance->unbindmodel(array('belongsTo' => array("Meeting")));
        $secretariat=$this->Decision->Meeting->Attendance->getMember($this->meetingList['Meeting']['id'],1);
        foreach($secretariat as $skey=>$sec){
            $this->Decision->Meeting->sendEmail($this->meetingList['Meeting'],$template,$sec['User'],null);
        }
         $this->Session->setFlash(__('The notification has been sent to secretariat',true));
        $this->redirect($this->meetingList['Link']['decision']);
        
    }
    
    function generatetemplate($committee,$id){
        $meeting=$this->Decision->Meeting->find('first',array('conditions'=>array('Meeting.id'=>$id)));
        $agenda=$meeting['Meeting']['agenda'];
        if(!empty($agenda)){
            $agenda=explode('<br />',nl2br($agenda));
            foreach($agenda as $ak=>$a){
                if(!empty($a)){
                    $a=explode('.',$a);
                    if(!empty($a[1])){
                        $info['Decision']['description']='<strong><span style="text-decoration: underline;">'.(substr($a[1],1)).'</span></strong>';
                        $info['Decision']['meeting_id']=$id;
                        $info['Decision']['committee_id']=$this->dcommittee['Committee']['id'];
                        $this->Decision->create();
                        $this->Decision->save($info);
                    }
                }
            }
        }
        $this->redirect(array('action'=>'minutes','committee'=>$committee,'id'=>$id));
    }
    
    //duplicate a same decision and mark down the decision which will be pasted
    function copy($committee,$decision_id){
        $decision=$this->Decision->find('first',array('conditions'=>array('Decision.id'=>$decision_id)));
        $decision_copy['Decision']=$decision['Decision'];
        unset($decision_copy['Decision']['id']);
        $meeting_id=$decision_copy['Decision']['meeting_id'];
        $decision_copy['Decision']['meeting_id']=0;
        $this->Decision->create();
        if($this->Decision->save($decision_copy)){
            $id=$this->Decision->getLastInsertID();
            $this->Session->write('decision_id',array('id'=>$id,'meeting_id'=>$meeting_id));
            if(!empty($decision['User'])){
                foreach ($decision['User'] as $ikey=>$i){
                    $this->Decision->DecisionsUser->create();
                    $idata['DecisionsUser']['decision_id']=$id;
                    $idata['DecisionsUser']['user_id']=$i['id'];
                    $this->Decision->DecisionsUser->save($idata);
                }
            }
            if(!empty($decision['Group'])){
                foreach ($decision['Group'] as $ikey=>$i){
                    $this->Decision->DecisionsUser->create();
                    $idata['DecisionsGroup']['decision_id']=$id;
                    $idata['DecisionsGroup']['group_id']=$i['id'];
                    $this->Decision->DecisionsGroup->save($idata);
                }
            }
        }
    }

    //mark down the decision which will be moved
    function cut($committee,$decision_id,$meeting_id){
        $this->Session->write('decision_id',array('id'=>$decision_id,'meeting_id'=>$meeting_id));
    }
    
    //paste the decision as next item of referred item
    function paste($committee,$decision_id){
        $this->Decision->recursive=-1;
        
        $mdecisions=$this->Session->read('decision_id');
        
        //find referred item
        $decision_base=$this->Decision->find('first',array('conditions'=>array('Decision.id'=>$decision_id)));
        
        if($mdecisions['meeting_id']==$decision_base['Decision']['meeting_id']){
        
            // find moved item
            $decision_move=$this->Decision->find('first',array('conditions'=>array('Decision.id'=>$mdecisions['id'])));
        
            //if referred item is child of the moved item, change it be childe of parent of moved item
            if($decision_base['Decision']['parent_id']==$decision_move['Decision']['id']){
                $decision_base['Decision']['parent_id']=$decision_move['Decision']['parent_id'];
                $this->Decision->save($decision_base);
            }
        
            //this for copy 
            $decision_move['Decision']['meeting_id']=$decision_base['Decision']['meeting_id'];
        
            //change the moved item parent and all the child under this parent
            if(!empty($decision_base['Decision']['parent_id']) && $decision_base['Decision']['parent_id']!=$decision_base['Decision']['id']){
                $decision_move['Decision']['parent_id']=$decision_base['Decision']['parent_id'];
                $decision_up=$this->Decision->find('all',array('order'=>array('Decision.lft ASC'),'conditions'=>array('Decision.deleted'=>0,'Decision.id!='.$mdecisions['id'],'Decision.id!='.$decision_base['Decision']['parent_id'],'Decision.parent_id'=>$decision_base['Decision']['parent_id'],'Decision.lft<='.$decision_base['Decision']['lft'])));
                $decision_down=$this->Decision->find('all',array('order'=>array('Decision.lft ASC'),'conditions'=>array('Decision.deleted'=>0,'Decision.id!='.$mdecisions['id'],'Decision.id!='.$decision_base['Decision']['parent_id'],'Decision.parent_id'=>$decision_base['Decision']['parent_id'],'Decision.lft>'.$decision_base['Decision']['lft'])));
            }else{
                $decision_move['Decision']['parent_id']=0;
                $meeting_decisions=$this->Decision->find('all',array('order'=>array('Decision.lft ASC'),'conditions'=>array('Decision.deleted'=>0,'Decision.meeting_id'=>$decision_base['Decision']['meeting_id'])));
                $decision_up=array();
                $decision_down=array();
                foreach($meeting_decisions as $md=>$mdecision){
                    if((empty($mdecision['Decision']['parent_id']) || $mdecision['Decision']['parent_id']==$mdecision['Decision']['id']) && $mdecision['Decision']['id']!=$mdecisions['id']){
                        if($mdecision['Decision']['lft']<=$decision_base['Decision']['lft']){
                            $decision_up[]=$mdecision;
                        }else{
                            $decision_down[]=$mdecision;
                        }
                    }
                }
            }
        
            $decision_move['Decision']['ordering']=$decision_base['Decision']['ordering']+1;
            $this->Decision->save($decision_move);
        
            //rearrange the lft and rght
            $decision_up_order['id']=set::extract($decision_up,'{n}.Decision.id');
            $decision_up_order['lft']=set::extract($decision_up,'{n}.Decision.lft');
            $decision_up_order['rght']=set::extract($decision_up,'{n}.Decision.rght');
        
            if(empty($decision_down)){
                $decision_down_order['id']=array();
                $decision_down_order['lft']=array();
                $decision_down_order['rght']=array();
            }else{
                $decision_down_order['id']=set::extract($decision_down,'{n}.Decision.id');
                $decision_down_order['lft']=set::extract($decision_down,'{n}.Decision.lft');
                $decision_down_order['rght']=set::extract($decision_down,'{n}.Decision.rght');
            }
        
            $order=array_merge($decision_up_order['lft'],$decision_up_order['rght'],$decision_down_order['lft'],$decision_down_order['rght']);
            $order[]=$decision_move['Decision']['lft'];
            $order[]=$decision_move['Decision']['rght'];
            sort($order);
            $order_move=array_splice($order,count($decision_up)*2);

            if(!empty($decision_up)){
                $this->Decision->rearrange($decision_up_order,$order);
            }
        
            $order_down=array_splice($order_move,2);
            $decision_move['Decision']['lft']=min($order_move);
            $decision_move['Decision']['rght']=max($order_move);
            $this->Decision->save($decision_move);
            if(!empty($decision_down)){
                $this->Decision->rearrange($decision_down_order,$order_down);
            }
        }
        $this->Session->delete('decision_id');
        
        $this->Decision->reordering($decision_base['Decision']['meeting_id']);
    }
    
    //paste the decision as subitem of referred item
    function pastesub($committee,$decision_id){
        $this->Decision->recursive=-1;
        
        $mdecision=$this->Session->read('decision_id');
        $decision=$this->Decision->find('first',array('conditions'=>array('Decision.id'=>$decision_id)));
        if($decision['Decision']['meeting_id']==$mdecision['meeting_id']){
            $this->Decision->reordering($decision['Decision']['meeting_id']);
            $decision_move=$this->Decision->find('first',array('conditions'=>array('Decision.id'=>$mdecision['id'])));
            if($decision['Decision']['parent_id']==$decision_move['Decision']['id']){
                $decision['Decision']['parent_id']=$decision_move['Decision']['parent_id'];
                $this->Decision->save($decision);
            }
            $decision_move['Decision']['meeting_id']=$decision['Decision']['meeting_id'];
            $decision_move['Decision']['parent_id']=$decision_id;
            $decision_move['Decision']['ordering']=$decision['Decision']['ordering']+1;
            $decision_move['Decision']['deleted']=0;
            $this->Decision->save($decision_move,false);
            $this->Session->delete('decision_id');
            $this->Decision->reordering($decision['Decision']['meeting_id']);
        }
    }
   
}
    
?>
